#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define per(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
const int N = 25;

int n, m;
int a[N][N];
ll pow10[N << 1];
set<int> st[N][N];
set<int> st2[N][N];
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  cin >> n >> m;
  rep(i, 1, n) rep(j, 1, n) cin >> a[i][j];
  // preprocessing
  pow10[0] = 1;
  rep(i, 1, n * 2) pow10[i] = pow10[i - 1] * 10ll % m;
  rep(i, 1, n) rep(j, 1, n) a[i][j] = a[i][j] * pow10[n * 2 - i - j] % m;

  st[1][1].insert(a[1][1]);
  rep(i, 1, n) rep(j, 1, n + 1 - i) {
    if (i > 1) {
      for (int x : st[i - 1][j]) {
        st[i][j].insert((x + a[i][j]) % m);
      }
    }
    if (j > 1) {
      for (int x : st[i][j - 1]) {
        st[i][j].insert((x + a[i][j]) % m);
      }
    }
  }

  rep(i, 1, n) a[i][n + 1 - i] = 0;
  st2[n][n].insert(a[n][n]);
  per(i, n, 1) per(j, n, n + 1 - i) {
    if (i < n) {
      for (int x : st2[i + 1][j]) {
        st2[i][j].insert((x + a[i][j]) % m);
      }
    }
    if (j < n) {
      for (int x : st2[i][j + 1]) {
        st2[i][j].insert((x + a[i][j]) % m);
      }
    }
  }

  int ans = 0;
  rep(i, 1, n) {
    int j = n + 1 - i;
    for (int x : st[i][j]) {
      int y = m - 1 - x;
      auto it = st2[i][j].upper_bound(y);
      if (it != st2[i][j].begin()) {
        it = prev(it);
        y = *it;
      } else {
        y = *st2[i][j].rbegin() - m;
      }
      ans = max(ans, x + y);
    }
  }
  cout << ans;
  return 0;
}